// pages/Second/Second.js

Page({

  /**
   * 页面的初始数据
   */
  data: {
    wulimodel: true,
    HideSchedule: true,
    CustID: 0,
    UnionstoreID: 0,
    Activity: null,
    ProductList: null,
    Schedules: null,
    imgDomain: ""
  },
  wulimodel: function() {
    this.setData({
      wulimodel: false,
    })
  },
  wuliclose: function() {
    this.setData({
      wulimodel: true,
    })
  },
  tabchange: function(e) {
    var schedule = e.currentTarget.dataset.schedule;
    var Schedules = this.data.Schedules;
    for (var i = 0; i < Schedules.length; i++) {
      if (Schedules[i].Schedule == schedule) {
        Schedules[i].Display = "show";
        Schedules[i].Css = "active";
      } else {
        Schedules[i].Display = "hidden";
        Schedules[i].Css = "";
      }
    }
    this.setData({
      Schedules: Schedules

    })
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    var globalData = getApp().globalData;
    var shopID = 0;
    if (options.shopID > 0) {
      shopID = options.shopID;
    }
    that.setData({
      CustID: globalData.custID,
      UnionstoreID: shopID
    });

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

    var that = this;
    that.LoadActivity();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  LoadActivity: function() {

    var that = this;
    var url = "/mobile/api/Activity/GetNowSecondKillActivity";
    var data = {
      custId: that.data.CustID,
      unionStoreID: that.data.UnionstoreID
    };
    var globalData = getApp().globalData;
    that.GetData(url, data, function(response) {
      var responseData = response.data;
      if (responseData.code == 1200 && responseData.content != null) {
        that.setData({
          Activity: responseData.content,
          imgDomain: globalData.imgurl
        });
        if (that.data.Activity.Schedule != null && that.data.Activity.Schedule != "") {
          var ScheduleList = that.data.Activity.Schedule.split(",");
          var list = new Array();
          var now = new Date();
          for (var i = 0; i < ScheduleList.length; i++) {
            var ti = ScheduleList[i];
            var schedule = new Schedule();
            schedule.Schedule == ti;
            var NowTime = new Date();
            var hh = NowTime.getHours();
            var hour = "";
            var scheduleHour = ti.split(":")[0];
            if (hh < 10)
              hour = "0" + hh + ":00";
            if (hh == scheduleHour) {
              schedule.Status = "秒杀中";
              schedule.StatusStr = "正在秒杀中";
              schedule.EndDiscribr = "距活动结束";
              schedule.TimeHide = true;
            } else if (hh > scheduleHour) {
              schedule.Status = "已开抢";
              schedule.StatusStr = "已开抢";
              schedule.EndDiscribr = "距活动结束";
              schedule.TimeHide = true;
            } else if (hh < scheduleHour) {
              schedule.Status = "即将开始";
              schedule.StatusStr = "即将开始秒杀";
              schedule.EndDiscribr = "距活动开始";
              schedule.TimeHide = false;
            }
            var y = NowTime.getFullYear();
            var m = NowTime.getMonth() + 1;
            var d = NowTime.getDate();

            if (m.toString().length <= 1) {
              m = "0" + m;
            }
            if (d.toString().length <= 1) {
              d = "0" + d;
            }

            schedule.timestart = y + "-" + m + "-" + d + " " + ti + ":01";

            schedule.timeout = that.data.Activity.Tomorrow;
            var display = "hidden";
            if (i == 0) {
              schedule.Css = "active";
              display = "show";
            }
            schedule.Schedule = ti;
            schedule.Display = display;
            list.push(schedule);

          }

          that.setData({
            Schedules: list,
            HideSchedule: false
          });
          that.LoadProduct();
          that.StartTimer();
        } else {
          var schedule = new Schedule();
          schedule.Schedule == "普通秒杀";
          schedule.timestart = that.data.Activity.BeginDt;

          schedule.timeout = that.data.Activity.EndDt;
          var NowTime = new Date();
          var timestart = that.ChansferDate(that.data.Activity.BeginDt);
          var timeout = that.ChansferDate(that.data.Activity.EndDt);
          if ((NowTime - timestart) > 0 && (timeout - NowTime) > 0) {
            schedule.Status = "秒杀中";
            schedule.StatusStr = "正在秒杀中";
            schedule.EndDiscribr = "距活动结束";
          } else if ((NowTime - timeout) >= 0) {
            schedule.Status = "已结束";
            schedule.StatusStr = "秒杀已结束";
            schedule.EndDiscribr = "距活动结束";
          } else if ((timestart - NowTime) > 0) {
            schedule.Status = "即将开始";
            schedule.StatusStr = "即将开始秒杀";
            schedule.EndDiscribr = "距活动开始";
          }
          schedule.TimeHide = false;
          var ls = new Array();
          ls.push(schedule);

          schedule.Display = "show";
          that.setData({
            Schedules: ls,
            HideSchedule: true
          });
          that.LoadProduct();
          that.StartTimer();
        }
      }
    });

  },
  GetData: function(url, data, callBack) {
    var globalData = getApp().globalData;
    wx.request({
      url: globalData.apiurl + url,
      data: data,
      method: 'GET',
      header: {
        'content-type': 'application/json',
        'X_ManuName': globalData.manuName
      },
      success: callBack,
      fail: function() {

      },
      complete: function() {
        //complete
      }
    })
  },
  LoadProduct: function() {
    var that = this;
    var Schedules = that.data.Schedules;
    var activityId = that.data.Activity.ID;
    if (Schedules != null) {
      for (var i = 0; i < Schedules.length; i++) {
        var schedule = Schedules[i].Schedule;
        that.LoadProductBySchedule(activityId, schedule, Schedules[i].Status);
      }



    }



  },
  LoadProductBySchedule: function(activityId, schedule, scheduleStatus) {
      var that = this;
      var url = "/mobile/api/Activity/GetActivityProductList";
      var data = {
        custId: that.data.CustID,
        activityId: activityId,
        schedule: schedule,
        unionStoreID: that.data.UnionstoreID,
        pageIndex: 1,
        pageSize: 50
      };
      that.GetData(url, data, function(response) {
        if (response.data.code == 1200 && response.data.content != null && response.data.content.Data != null) {
          var data = response.data.content.Data;
          if (data != null && data.length > 0) {
            for (var i = 0; i < data.length; i++) {
              var Stock = 0;
              var AllStockNum = 0;
              var secondkillPrice = data[i].CurrentPrice;
              if (data[i].ActivityProduct != null && data[i].ActivityProduct.length > 0) {
                secondkillPrice = data[i].ActivityProduct[0].CashNum;
                Stock += data[i].ActivityProduct[0].StockNum;
                AllStockNum += data[i].ActivityProduct[0].AllStockNum;
                for (var j = 1; j < data[i].ActivityProduct.length; j++) {
                  var p = data[i].ActivityProduct[j];
                  if (p.CashNum < secondkillPrice) {
                    secondkillPrice = p.CashNum;
                  }
                  Stock += p.StockNum;
                  AllStockNum += p.AllStockNum;
                }
              }
              data[i].secondkillPrice = secondkillPrice;
              if (Stock == 0) {
                data[i].ButtonText = "售罄";
                data[i].ButtonCss = "btn1";
              } else {
                data[i].ButtonText = "立即秒杀"
                data[i].ButtonCss = ""
              }

              if (scheduleStatus == "即将开始") {
                data[i].ButtonText = "即将开始"
                data[i].ButtonCss = ""
              }
              var stockPercent = 0;
              if (AllStockNum > 0) {
                stockPercent = parseInt((AllStockNum-Stock) * 100.0 / AllStockNum);
              }
            
              data[i].StockPercent = stockPercent;

            }

            var ProductList = that.data.ProductList;
            if (ProductList == null) {
              ProductList = new Array();
            }
            var obj = new Object();
            obj.schedule = schedule;
            var haveProducts = new Array();
            var noProducts = new Array();
            for (var i = 0; i < data.length; i++) {
              if (data[i].ButtonText == "售罄") {
                noProducts.push(data[i]);
              } else {
                haveProducts.push(data[i]);
              }
            }
            obj.data = haveProducts.concat(noProducts);;
            ProductList.push(obj);
            that.setData({
              ProductList: ProductList
            });
          }



        }
      });

    }

    ,
  StartTimer: function() {
    var that = this;
    setInterval(function() {
      var Schedules = that.data.Schedules;
      for (var i = 0; i < Schedules.length; i++) {
        var timestart = that.ChansferDate(Schedules[i].timestart);
        var timeout = that.ChansferDate(Schedules[i].timeout);
        var nowTime = new Date();

        var t = 0;
        //已经开始
        if ((timeout - nowTime) > 0 && (nowTime - timestart) > 0) {

          t = timeout - nowTime;
        }
        //还没开始
        if ((timestart - nowTime) > 0) {
          t = timestart - nowTime;

        }




        if (t > 0) {
          var d = Math.floor(t / 1000 / 60 / 60 / 24);
          var h = Math.floor(t % (24 * 3600 * 1000) / 1000 / 60 / 60);
          var m = Math.floor(t / 1000 / 60 % 60);
          var s = Math.floor(t / 1000 % 60);

          if (h.toString().length <= 1) {
            h = "0" + h;
          }
          if (m.toString().length <= 1) {
            m = "0" + m;
          }
          if (s.toString().length <= 1) {
            s = "0" + s;
          }
          Schedules[i].TimerDate = d;
          Schedules[i].TimerHour = h;
          Schedules[i].TimerMinute = m;
          Schedules[i].TimerSecond = s;
        }
      }
      that.setData({
        Schedules: Schedules
      });

    }, 1000);






  },
  ChansferDate: function(strdate) {
    var arr = strdate.split(/[- : \/]/);
    var date = new Date(arr[0], arr[1] - 1, arr[2], arr[3], arr[4], arr[5]);
    return date;

  }

})


function Schedule() {
  this.Css = "";
  this.Schedule = "";
  this.Status = "";
  this.StatusStr = "";
  this.EndDiscribr = "";
  this.ProductList = null;
  this.TimerDate = "0";
  this.TimerHour = "00";
  this.TimerMinute = "00";
  this.TimerSecond = "00";
}